package com.example.apisimpledy.service.impl;

import com.example.apisimpledy.entity.dto.MyUser;
import com.example.apisimpledy.repository.MyUserRepository;
import com.example.apisimpledy.service.MyUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.Instant;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;


@Service
public class MyUserServiceImpl implements MyUserService {

    @Autowired
    private MyUserRepository myUserRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;



    @Override
    public UserDetails loadUserByUsername(String nameOrEmail) throws UsernameNotFoundException {
        MyUser myUser = this.findByNameOrEmail(nameOrEmail);
        System.out.println(myUser);
        if (myUser == null) throw new UsernameNotFoundException("用户名或密码错误");

        Set<String> roles = myUser.getRoles();
        String[] roleNames = roles.toArray(new String[0]);

        return User
                .withUsername(nameOrEmail)
                .password(myUser.getPassword())
                .roles(roleNames)//注意这里是多个Role所形成的字符串
                .build();
    }

    @Override
    public MyUser findByNameOrEmail(String nameOrEmail) {
        return myUserRepository.findByUsernameOrEmail(nameOrEmail, nameOrEmail).orElse(null);
    }

    @Override
    public MyUser registerUser(String username, String password, String email) {
        Optional<MyUser> existingUser = myUserRepository.findByUsernameOrEmail(username, email);
        if (existingUser.isPresent()) {
            throw new RuntimeException("Username or Email is already taken!");
        }

        Set<String> roles = new HashSet<>();
        roles.add("user");  // 添加默认角色

        MyUser newUser = new MyUser();
        newUser.setUsername(username)
                .setPassword(passwordEncoder.encode(password))
                .setEmail(email)
                .setCreatedAt(Timestamp.from(Instant.now()))
                .setRoles(roles);  // 设置默认角色

        return myUserRepository.save(newUser);
    }


}
